package com.gs.wzmanager.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by haol on 2016/9/4.
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String login() {
        return "user/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String checkLogin(@RequestParam String phone, @RequestParam String password) {
        logger.info("go into UserCon");
        //得到subject，其会自动绑定到当前线程
        Subject subject = SecurityUtils.getSubject();
        //创建用户名/密码身份验证Token
        UsernamePasswordToken token = new UsernamePasswordToken(phone, password);
        try {
            /*调用Subject.login进行登录，其会自动委托给Security Manager,
             *SecurityManager负责真正的身份验证逻辑；它会委托给Authenticator进行身份验证；
             *Authenticator会把相应的token传入Realm，从Realm获取身份验证信息，如果没有返回/抛出异常表示身份验证失败了。
             *此处可以配置多个Realm，将按照相应的顺序及策略进行访问。
             *如果失败将得到相应的AuthenticationException异常，根据异常提示用户错误信息；否则登录成功
             */
            subject.login(token);
            return "redirect:/user/listView";
        } catch (AuthenticationException e) {
            logger.error(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return "user/login";
    }

    @RequestMapping(value = "/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login/index";
    }
}
